import { defineStore } from "pinia";
import {
  login,
  logout,
  loginByPassword,
  register,
  getUserInfo,
} from "@/api/login";
import { StorageService } from "@/utils/storage";
import { maskPhoneNumber } from "@/utils/phoneUtils";
const STORAGE_KEYS = {
  TOKEN: "Token",
  REFRESH_TOKEN: "REFRESH_TOKEN",
  USER_INFO: "userInfo",
  PHONE: "phone",
  PHONE_MASKED: "maskedPhone",
};

export const useAuthStore = defineStore("auth", {
  state: () => ({
    token: StorageService.get(STORAGE_KEYS.TOKEN),
    refreshToken: StorageService.get(STORAGE_KEYS.REFRESH_TOKEN),
    userInfo: null,
    permissions: [],
    phone: StorageService.get(STORAGE_KEYS.PHONE) || "",
    maskedPhone: StorageService.get(STORAGE_KEYS.PHONE_MASKED) || "",
  }),

  getters: {
    isAuthenticated: (state) => Boolean(state.token),
    hasUserInfo: (state) => Boolean(state.userInfo),
  },

  actions: {
    clearAuthData() {
      this.token = null;
      this.refreshToken = null;
      this.userInfo = {};
      this.permissions = [];
      this.phone = "";
      this.maskedPhone = "";

      Object.values(STORAGE_KEYS).forEach((key) => {
        StorageService.remove(key);
      });
    },

    setAuthData({ token, refresh: refreshToken, phone }) {
      if (!token || !refreshToken) {
        throw new Error("Invalid authentication data");
      }

      this.token = token;
      this.refreshToken = refreshToken;
      this.phone = phone;
      this.maskedPhone = maskPhoneNumber(phone);

      StorageService.set(STORAGE_KEYS.TOKEN, token);
      StorageService.set(STORAGE_KEYS.REFRESH_TOKEN, refreshToken);
      StorageService.set(STORAGE_KEYS.PHONE, phone);
      StorageService.set(STORAGE_KEYS.PHONE_MASKED, this.maskedPhone);
    },

    async authenticate(credentials, authMethod) {
      try {
        const response = await authMethod(credentials);

        if (!response?.data) {
          throw new Error("Invalid authentication response");
        }
        this.setAuthData(response.data);
        await this.fetchUserInfo();
        return response.data;
      } catch (error) {
        this.clearAuthData();
        throw error;
      }
    },

    async login(credentials) {
      return this.authenticate(credentials, login);
    },

    async loginByPassword(credentials) {
      return this.authenticate(credentials, loginByPassword);
    },

    async register(userData) {
      return this.authenticate(userData, register);
    },

    async fetchUserInfo() {
      try {
        const response = await getUserInfo();

        if (!response?.data) {
          throw new Error("Failed to fetch user info");
        }

        const { permissions = [], ...userInfo } = response.data;
        this.userInfo = userInfo;
        this.permissions = permissions;

        return response.data;
      } catch (error) {
        this.clearAuthData();
        throw error;
      }
    },

    async logout() {
      try {
        // await logout();
      } catch (error) {
        console.error("Logout failed:", error);
      } finally {
        this.clearAuthData();
      }
    },
  },
});
